package io.fft.flight.modules.flight.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.fft.flight.common.annotation.DictTranslate;
import io.fft.flight.common.exception.RenExceptionEnum;
import io.fft.flight.common.service.impl.CrudServiceImpl;
import io.fft.flight.common.utils.C;
import io.fft.flight.common.utils.J;
import io.fft.flight.modules.flight.dao.OrderSegmentDao;
import io.fft.flight.modules.flight.dto.OrderDTO;
import io.fft.flight.modules.flight.dto.order.OrderNotifyBaseDTO;
import io.fft.flight.modules.flight.dto.order.OrderNotifyDTO;
import io.fft.flight.modules.flight.dto.order.segment.OrderNotifySegmentDTO;
import io.fft.flight.modules.flight.dto.order.segment.OrderNotifySegmentRuleDTO;
import io.fft.flight.modules.flight.entity.*;
import io.fft.flight.modules.flight.enums.SegmentRuleTypeEnum;
import io.fft.flight.modules.flight.service.*;
import io.fft.flight.modules.flight.dao.OrderDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户订单
 *
 * @author likailun kellenli30541@gmail.com
 * @since 1.0.0 2023-06-20
 */
@Slf4j
@Service
public class OrderServiceImpl extends CrudServiceImpl<OrderDao, OrderEntity, OrderDTO> implements OrderService {

    @Resource
    private OrderSegmentService orderSegmentService;
    @Resource
    private OrderPassengerService orderPassengerService;
    @Resource
    private OrderSegmentPolicyService segmentPolicyService;
    @Resource
    private OrderSegmentRuleService orderSegmentRuleService;
    @Resource
    private OrderSegmentRuleDetailService orderSegmentRuleDetailService;
    @Resource
    private OrderPriceService orderPriceService;
    @Resource
    private OrderPolicyService orderPolicyService;

    @Override
    public QueryWrapper<OrderEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");
        String orderNo = (String) params.get("orderNo");

        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(orderNo), "order_no", orderNo);
        return wrapper;
    }


    @Transactional
    @Override
    public boolean orderNotify(OrderNotifyDTO dto) {
        if (StringUtils.isEmpty(dto.getRqData())) {
            return false;
        }
        // 解码Base64编码的字符串
        byte[] decodedBytes = Base64.getDecoder().decode(dto.getRqData());
        // 将字节转换成字符串
        String reqStr = new String(decodedBytes);
        final OrderNotifyBaseDTO order = J.object2Entity(reqStr, OrderNotifyBaseDTO.class);
        if (null == order) {
            return false;
        }
        log.info("接收到订单通知：{}", J.jsonStr(order));
        final List<OrderEntity> orders = this.baseDao.selectList(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderNo, order.getOrderNo()));
        if (C.isEmpty(orders)) {
            final OrderEntity orderEntity = J.object2Entity(order, OrderEntity.class);
            orderEntity.setCreateAte(new Date());
            orderEntity.setCreator(0L);
            insert(orderEntity);
            log.info("插入主订单");
            // 航段信息处理
            if (C.isNotEmpty(order.getSegmentList())) {
                final List<OrderSegmentEntity> segmentEntities = J.object2Array(order.getSegmentList(), OrderSegmentEntity.class);
                for (OrderSegmentEntity segmentEntity : segmentEntities) {
                    segmentEntity.setCreateDate(new Date());
                    segmentEntity.setOrderNo(orderEntity.getOrderNo());
                    segmentEntity.setCreator(0L);
                }
                orderSegmentService.insertBatch(segmentEntities);
                for (OrderSegmentEntity segmentEntity : segmentEntities) {
                    OrderNotifySegmentDTO orderNotifySegmentDTO = order.getSegmentList().stream().filter(s -> s.getSegmentNo().equals(segmentEntity.getSegmentNo())).findFirst().get();
                    // 航段政策信息
                    if (null != orderNotifySegmentDTO.getDomPolicy()) {
                        OrderSegmentPolicyEntity orderSegmentPolicyEntity = J.object2Entity(orderNotifySegmentDTO.getDomPolicy(), OrderSegmentPolicyEntity.class);
                        orderSegmentPolicyEntity.setCreator(0L);
                        orderSegmentPolicyEntity.setCreateDate(new Date());
                        orderSegmentPolicyEntity.setOrderSegmentId(segmentEntity.getId());
                        segmentPolicyService.insert(orderSegmentPolicyEntity);
                    }
                    // 航段规则
                    if (null != orderNotifySegmentDTO.getRule()) {
                        OrderSegmentRuleEntity orderSegmentRuleEntity = J.object2Entity(orderNotifySegmentDTO.getRule(), OrderSegmentRuleEntity.class);
                        orderSegmentRuleEntity.setOrderNo(orderEntity.getOrderNo());
                        orderSegmentRuleEntity.setCreator(0L);
                        orderSegmentRuleEntity.setOrderSegmentId(segmentEntity.getId());
                        orderSegmentRuleEntity.setRuleType(Integer.valueOf(Optional.ofNullable(orderNotifySegmentDTO.getRule().getRuleType()).orElse("0")));
                        orderSegmentRuleService.insert(orderSegmentRuleEntity);

                        // 改签规则
                        if (null != orderNotifySegmentDTO.getRule().getChaRule()) {
                            OrderSegmentRuleDetailEntity orderSegmentRuleDetailEntity = J.object2Entity(orderNotifySegmentDTO.getRule().getChaRule(), OrderSegmentRuleDetailEntity.class);
                            orderSegmentRuleDetailEntity.setCreator(0L);
                            orderSegmentRuleDetailEntity.setCreateDate(new Date());
                            orderSegmentRuleDetailEntity.setSegmentRuleId(orderSegmentRuleEntity.getOrderSegmentId());
                            orderSegmentRuleDetailEntity.setRuleType(SegmentRuleTypeEnum.CHANGE.getCode());
                            orderSegmentRuleDetailService.insert(orderSegmentRuleDetailEntity);
                        }

                        // 退票规则
                        if (null != orderNotifySegmentDTO.getRule().getRefRule()) {
                            OrderSegmentRuleDetailEntity orderSegmentRuleDetailEntity = J.object2Entity(orderNotifySegmentDTO.getRule().getRefRule(), OrderSegmentRuleDetailEntity.class);
                            orderSegmentRuleDetailEntity.setCreator(0L);
                            orderSegmentRuleDetailEntity.setCreateDate(new Date());
                            orderSegmentRuleDetailEntity.setSegmentRuleId(orderSegmentRuleEntity.getOrderSegmentId());
                            orderSegmentRuleDetailEntity.setRuleType(SegmentRuleTypeEnum.REFUND.getCode());
                            orderSegmentRuleDetailService.insert(orderSegmentRuleDetailEntity);
                        }
                    }
                }
            }
            // 乘客信息
            if (C.isNotEmpty(order.getPassengerList())) {
                final List<OrderPassengerEntity> passengerEntities = J.object2Array(order.getPassengerList(), OrderPassengerEntity.class);
                for (OrderPassengerEntity passengerEntity : passengerEntities) {
                    passengerEntity.setCreateDate(new Date());
                    passengerEntity.setOrderNo(orderEntity.getOrderNo());
                    passengerEntity.setCreator(0L);
                }
                orderPassengerService.insertBatch(passengerEntities);
            }

            // 乘客信息
            if (null != order.getSupplierOrderPrice()) {
                OrderPriceEntity orderPriceEntity = J.object2Entity(order.getSupplierOrderPrice(), OrderPriceEntity.class);
                orderPriceEntity.setOrderNo(order.getOrderNo());
                orderPriceEntity.setCreator(0L);
                orderPriceEntity.setCreateDate(new Date());
                orderPriceService.insert(orderPriceEntity);
            }

            // 政策信息
            if (null != order.getSupplierPolicyDetailList()) {
                OrderPolicyEntity orderPolicyEntity = J.object2Entity(order.getSupplierPolicyDetailList(), OrderPolicyEntity.class);
                orderPolicyEntity.setOrderNo(order.getOrderNo());
                orderPolicyEntity.setCreator(0L);
                orderPolicyEntity.setCreateDate(new Date());
                orderPolicyService.insert(orderPolicyEntity);
            }
            return true;
        }
        return false;
    }

    @Override
    public OrderNotifyBaseDTO queryDetail(String orderNo) {
        List<OrderEntity> orders =
                this.baseDao.selectList(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderNo, orderNo));
        RenExceptionEnum.NOT_EXIT.assertNotEmpty(orders);

        return null;
    }
}